package com.kj.xuyuan.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kj.xuyuan.R;
import com.kj.xuyuan.adapter.SelectImageAdapter;
import com.kj.xuyuan.base.BaseActivity;
import com.kj.xuyuan.base.BaseModel;
import com.kj.xuyuan.base.Constants;
import com.kj.xuyuan.base.MyApp;
import com.kj.xuyuan.http.JsonCallback;
import com.kj.xuyuan.http.JsonNoEncryptionCallback;
import com.kj.xuyuan.http.OkGoUtil;
import com.kj.xuyuan.http.UrlConstants;
import com.kj.xuyuan.model.UploadBean;
import com.kj.xuyuan.util.DisplayUtil;
import com.kj.xuyuan.util.LogUtils;
import com.kj.xuyuan.util.PhotoSelectSingleUtile;
import com.kj.xuyuan.util.StringUtils;
import com.kj.xuyuan.util.ToastUtil;
import com.kj.xuyuan.widget.FullyGridLayoutManager;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PublishDynamicActivity extends BaseActivity {

    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.tv_publish)
    TextView tvPublish;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.ed_content)
    EditText edContent;
    @BindView(R.id.tv_content_words)
    TextView tvContentWords;
    @BindView(R.id.rv_image)
    RecyclerView rvImage;
    @BindView(R.id.tv_topic)
    TextView tvTopic;

    private int topicId;
    private String topicTitle;
    private List<LocalMedia> imageData;
    private SelectImageAdapter adapter;
    private int imageNum;
    private StringBuffer imageUrls;

    public static void actionStar(Context context, int topicId, String topicTitle) {
        Intent intent = new Intent(context, PublishDynamicActivity.class);
        intent.putExtra("topicId", topicId);
        intent.putExtra("topicTitle", topicTitle);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_publish_dynamic;
    }

    @Override
    protected void initView() {
        topicId = getIntent().getIntExtra("topicId",-1);
        if(topicId != -1){
            topicTitle = getIntent().getStringExtra("topicTitle");
            tvTopic.setText(topicTitle);
        }else{
            text.setVisibility(View.GONE);
            tvTopic.setVisibility(View.GONE);
        }

        initEditText();
        initRecyclerView();
    }

    private void initRecyclerView() {
        imageData = new ArrayList<>();
        imageData.add(new LocalMedia());
        adapter = new SelectImageAdapter();
        rvImage.setLayoutManager(new FullyGridLayoutManager(context,3));
        rvImage.addItemDecoration(new GridSpacingItemDecoration(3, DisplayUtil.dp2px(context,17),false));
        rvImage.setAdapter(adapter);
        adapter.setNewData(imageData);

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case R.id.iv_close:
                        imageData.remove(position);
                        if(imageData.size() == 8 && imageData.get(7).getBucketId() != -1){//当前有8张图，且最后一张不是添加按钮时添加按钮
                            imageData.add(new LocalMedia());
                        }
                        adapter.notifyDataSetChanged();
                        break;
                    case R.id.iv_image:
                        if(imageData.get(position).getBucketId() == -1){
                            imageData.remove(position);
                            PhotoSelectSingleUtile.selectPhoto(context, PictureMimeType.ofImage(),imageData, 9);
                        }
                        break;
                }
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                    imageData.clear();
                    if(localMedia.size() == 0){
                        imageData.add(new LocalMedia());
                    }else{
                        imageData.addAll(localMedia);
                        if (localMedia.size() < 9) {
                            imageData.add(new LocalMedia());
                        }
                    }
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    private void initEditText() {
        edContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                tvContentWords.setText(edContent.getText().toString().length()+"/1000");
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getTitleBarType() {
        return -1;
    }

    private void checkData() {
        if(imageData != null && imageData.size() == 1 && imageData.get(0).getBucketId() == -1){
            ToastUtil.showToast(context,"未选择图片");
            return;
        }
        String content = edContent.getText().toString().trim();
        if(StringUtils.isEmpty(content)){
            ToastUtil.showToast(context,"动态未填写");
            return;
        }
        showDialog();
        if(imageData.size() == 9){
            if(imageData.get(8).getBucketId() == -1){
                imageNum = 8;
            }else{
                imageNum = 9;
            }
        }else{
            imageNum = imageData.size()-1;
        }

        imageUrls = new StringBuffer();

        for(int i = 0;i<imageData.size();i++){
            uploadImage(imageData.get(i));
        }
    }

    private void uploadImage(LocalMedia localMedia) {
        if(localMedia.getBucketId() == -1){
            return;
        }
        File file = new File(MyApp.selectPhotoShow(context,localMedia));
        OkGoUtil.postSingleFile(context, UrlConstants.UPLOAD,file,new JsonNoEncryptionCallback<BaseModel<UploadBean>>() {
            @Override
            public void onSuccess(Response<BaseModel<UploadBean>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        imageUrls.append(response.body().getData().getUrl()).append(",");
                    }else{
                        ToastUtil.showToast(context,response.body().getMsg());
                    }
                    imageNum --;
                    if(imageNum == 0){
                        if(imageUrls.length() > 0){
                            imageUrls.deleteCharAt(imageUrls.length()-1);
                            publishDynamic();
                        }
                        dismissDialog();
                    }
                }
            }

            @Override
            public void onError(Response<BaseModel<UploadBean>> response) {
                super.onError(response);
                imageNum --;
                if(imageNum == 0){
                    if(imageUrls.length() > 0){
                        imageUrls.deleteCharAt(imageUrls.length()-1);
                        publishDynamic();
                    }
                    dismissDialog();
                }
                LogUtils.e(TAG,"response ="+response.getException());
            }
        });
    }

    private void publishDynamic() {
        Map map = new HashMap();

        map.put("type", "1");
        if(topicId != -1){
            map.put("id", topicId+"");
        }
        map.put("content", edContent.getText().toString().trim());
        map.put("address", Constants.PROVINCE+Constants.CITY);
        map.put("image", imageUrls.toString());

        OkGoUtil.postRequest(this, UrlConstants.PUBLISH_DYNAMIC, map, new JsonCallback<BaseModel<?>>() {
            @Override
            public void onSuccess(Response<BaseModel<?>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        finish();
                    }
                    ToastUtil.showToast(context,response.body().getMsg());
                }
            }

            @Override
            public void onError(Response<BaseModel<?>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
            }
        });
    }

    @OnClick({R.id.tv_cancel, R.id.tv_publish})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.tv_publish:
                checkData();
                break;
        }
    }
}